package boot3.service.impl;

import boot3.mapper.ChatroomMapper;
import boot3.mapper.LivechatMapper;
import boot3.mapper.NoticeMapper;
import boot3.mapper.UserMapper;
import boot3.pojo.Chatroom;
import boot3.service.ChatroomService;
import boot3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatroomServiceImpl implements ChatroomService {

    @Autowired
    private ChatroomMapper chatroomMapper;
    @Autowired
    private LivechatMapper livechatMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public List<Chatroom> findAll() {
        return chatroomMapper.findAll();
    }

    @Override
    public String createChatroom(String project_name, String start_time, String admin_id, Boolean isPrivate) {
        //先获取聊天室的长度
        int index= findAll().size()-1;
        String chatroomsLength=findAll().isEmpty()?"1001":findAll().get(index).getChatroom_id();
        String chatroom_id= String.valueOf(1+Integer.parseInt(chatroomsLength));
        //根据admin_id获取管理者的姓名
        String admin_name=userService.getUserName(admin_id);
        //创建聊天室
        chatroomMapper.createChatroom(chatroom_id, project_name, start_time, admin_id, isPrivate,admin_name);
        //更新一下聊天室的在线人数
        updateChatroom(chatroom_id);
        return chatroom_id;
    }

    @Override
    public Boolean deleteChatroom(String chatroom_id) {
        return chatroomMapper.deleteChatroom(chatroom_id) && noticeMapper.deleteNoticeByChatroomID(chatroom_id);
    }

    @Override
    public String getLiveroomAdminID(String chatroom_id) {
        return chatroomMapper.getLiveroomAdminID(chatroom_id);
    }

    @Override
    public void updateChatroom(String chatroom_id) {
        int onlineNumber=livechatMapper.getAllUsers(chatroom_id).size();
        chatroomMapper.updateChatroom(chatroom_id, onlineNumber);
    }

    @Override
    public Chatroom findChatroom(String chatroom_id) {
        return chatroomMapper.findChatroom(chatroom_id);
    }
}
